package exercises;

import java.io.*;
import java.util.*;

public class FileDeal {
    // 中文正则
    final static String REGEX_CHINESE = "[\u4e00-\u9fa5]";
//    （｜）|;|=|/|@|，|。|\?|.|:|\s+
//    final static String DELIM = "（）(){};=/@，。？！+,\\s?.!:\"\"' '\n";
    final static String DELIM = ",";
    String filePath;


    public FileDeal(String filePath) {
        this.filePath = filePath;
    }

    public Boolean inspectFile() {
        File file = new File(filePath);
        return file.exists() && !file.isDirectory() && file.length() != 0;
    }

    public Map dealFile() {
        Map<String, Integer> map = new LinkedHashMap<>();
        try {
            //读取文件
            FileInputStream fis = new FileInputStream(filePath);
            BufferedReader br = new BufferedReader(new InputStreamReader(fis));
            String temp;
            while((temp = br.readLine()) != null){
                temp = temp.replaceAll(REGEX_CHINESE, "").replaceAll("\\d+","");
//                System.out.println(temp);
                countWords(map, temp);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return map;
    }

    private void countWords(Map map, String temp) {
        // 分割字符串
        StringTokenizer st = new StringTokenizer(temp, DELIM); // 用于切分字符串
        //初始化计数器
        int count;
        //初始化word变量
        String word;
        while (st.hasMoreTokens()) {
            //逗号，问号，句号，感叹号，冒号，双引号，单引号，换行符号
            word = st.nextToken(DELIM);
//            System.out.println(word);
            if (map.containsKey(word)) {
                // HashMap 保存数据
                count = (int) map.get(word);
                //计数器累加
                map.put(word, count + 1);
            } else {
                map.put(word, 1);
            }
        }
    }
    public void outPut(Map map) throws IOException {
        System.out.println(map);
        List<Map.Entry<String, Integer>> list = new ArrayList<>(map.entrySet());
        File file = new File("output/countWords.txt");
        BufferedWriter bf = new BufferedWriter(new FileWriter(file));
        try {

            for (Map.Entry<String, Integer> entry : list) {
                System.out.println(entry.getKey() + ":" + entry.getValue());
                bf.write(entry.getKey() + ":" + entry.getValue());
                bf.newLine();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        finally {
            try {
                bf.close();
            }
            catch (Exception e) {

            }
        }
    }
}
